package com.huawei.codearts.tools.utils;


import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


public class HeaderUtils {

    public static String get(String key) {
        // 通过header头获取token数据
        String value = null;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                if (Objects.equals(headerName, key)) {
                    value = headerValue;
                    break;
                }
                // 这里可以处理header
//                System.out.println(headerName + ": " + headerValue);
            }
        }
        return value;
    }

    public static Map<String, String> get(String... keys) {
        // 通过header头获取token数据
        Map<String, String> valueMap = new ConcurrentHashMap<>();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                for (String key: keys) {
                    if (Objects.equals(headerName, key)) {
                        valueMap.put(key, headerValue);
                    }
                }
            }
        }
        return valueMap;
    }

    public static Map<String, String> get() {
        // 通过header头获取token数据
        Map<String, String> valueMap = new ConcurrentHashMap<>();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                valueMap.put(headerName, headerValue);
            }
        }
        return valueMap;
    }

}
